<template>
  <view class="goods-list-page">
    <!-- #ifdef MP-WEIXIN -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- #endif -->
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-container">
        <view class="back-btn" @click="goBack">
          <image class="back-icon" src="/static/Images/goods/Fanhui.png" mode="aspectFit"></image>
        </view>
        <view class="search-input" @click="goToSearch">
          <image class="search-icon" src="/static/Images/goods/Sousu.png" mode="aspectFit"></image>
          <input 
            class="search-real-input"
            v-model="kwd"
            confirm-type="search"
            placeholder="搜索商品名"
            @confirm="onSearch"
            @focus="goToSearch"
          />
          <view class="search-btn" @click.stop="goToSearch">
            <text class="search-btn-text">搜索</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类标签栏 -->
    <view class="category-tags">
      <view class="category-scroll" :class="{ expanded: isExpanded }">
        <view class="category-tags-container" :class="{ expanded: isExpanded }">
          <view 
            v-for="(category, index) in categoryTags" 
            :key="index"
            class="category-tag"
            :class="{ active: selectedCategoryIndex === index }"
            @click="onCategoryTagClick(category, index)"
          >
            <view class="category-circle" :class="{ active: selectedCategoryIndex === index }">
              <image v-if="category.icon" :src="category.icon" mode="aspectFit" class="category-icon" />
            </view>
            <text class="category-text" :class="{ active: selectedCategoryIndex === index }">{{ category.name }}</text>
          </view>
        </view>
      </view>
      <view class="expand-btn" @click="toggleCategoryExpand">
        <text class="expand-text">{{ isExpanded ? '收起' : '展开' }}</text>
        <image class="expand-icon" :class="{ rotated: isExpanded }" src="/static/Images/goods/Zhankai.png" mode="aspectFit"></image>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          v-for="(tab, index) in filterTabs" 
          :key="index"
          class="filter-tab"
          :class="{ active: selectedFilterIndex === index }"
          @click="onFilterTabClick(tab, index)"
        >
          <text class="filter-text" :class="{ active: selectedFilterIndex === index }">{{ tab.name }}</text>
          <view v-if="tab.hasDropdown" class="sort-icons">
            <image class="sort-icon sort-up" src="/static/Images/goods/Xiangxshang.png" mode="aspectFit"></image>
            <image class="sort-icon sort-down" src="/static/Images/goods/Xiangxia.png" mode="aspectFit"></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 二级筛选标签 -->
    <view class="sub-filter-section">
      <scroll-view class="sub-filter-scroll" scroll-x="true" show-scrollbar="false">
        <view class="sub-filter-container">
          <view 
            v-for="(filter, index) in subFilters" 
            :key="index"
            class="sub-filter-tag"
            :class="{ active: selectedSubFilterIndex === index }"
            @click="onSubFilterClick(filter, index)"
          >
            <text class="sub-filter-text" :class="{ active: selectedSubFilterIndex === index }">{{ filter.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <scroll-view 
        class="goods-scroll" 
        scroll-y="true"
        @scrolltolower="onScrollToLower"
        :style="{ height: scrollHeight }"
      >
        <view class="goods-container">
          <view 
            v-for="(goods, index) in goodsList" 
            :key="goods.id || index"
            class="goods-item"
            @click="onGoodsClick(goods)"
          >
            <view class="goods-image">
              <image 
                v-if="goods.imgs && goods.imgs.length > 0" 
                :src="safeImgUrl(goods.imgs[0])" 
                mode="aspectFill"
                class="goods-img"
              />
              <view class="goods-badge" v-if="goods.status === 1">{{ goods.badge || '新品' }}</view>
            </view>
            <view class="goods-info">
              <text class="goods-title">{{ goods.goods_name || goods.title }}</text>
              <text class="goods-stock">库存：{{ goods.num || goods.stock }}</text>
              <view class="goods-price-section">
                <text class="goods-price">¥{{ goods.price }}</text>
                <text class="goods-original-price" v-if="goods.cost_price && parseFloat(goods.cost_price) > 0">¥{{ goods.cost_price }}</text>
                <view class="buy-btn">
                  <text class="buy-text">立即购买</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-section">
            <text class="loading-text">加载中...</text>
          </view>
          
          <!-- 没有更多数据 -->
          <view v-if="!hasMore && goodsList.length > 0" class="no-more-section">
            <text class="no-more-text">没有更多数据了</text>
          </view>
          
          <!-- 暂无数据 -->
          <view v-if="!loading && goodsList.length === 0" class="empty-section">
            <text class="empty-text">暂无商品数据</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部指示器 -->
    <view class="home-indicator"></view>
  </view>
</template>

<script>
import { goodsApi } from '@/utils/api'

export default {
  data() {
    return {
      // 状态栏高度
      statusBarHeight: 0,
      selectedCategoryIndex: 0,
      selectedFilterIndex: 0,
      selectedSubFilterIndex: 0,
      isExpanded: false,
      // 二级分类标签，来源于 /api/goods/getGoodsClass 过滤 pid!=0
      categoryTags: [],
      filterTabs: [
        { name: '默认', hasDropdown: false },
        { name: '新品排序', hasDropdown: true },
        { name: '价格排序', hasDropdown: true },
        { name: '销量排序', hasDropdown: true }
      ],
      subFilters: [
        { name: '全部', id: 'all' },
        { name: '自动充值', id: 'auto' },
        { name: '卡密充值', id: 'card' },
        { name: '芒果TV会员', id: 'mango' },
        { name: '芒果TV', id: 'mango2' }
      ],
      goodsList: [],
      // 分页与加载状态
      page: 1,
      size: 10,
      hasMore: true,
      loading: false,
      kwd: '',
      // 选中的后端分类ID（由路由传入）
      classId: 0,
      // 搜索时强制的 type 值（例如 0 表示全部）；未设置时按 UI 二级筛选映射
      forcedType: undefined,
      // 为 H5 设置 scroll-view 高度，避免页面整体滚动导致 @scrolltolower 不触发
      scrollHeight: 'calc(100vh - 260px)'
    }
  },
  created() {
    // 等待 onLoad 解析路由参数后再触发首屏加载
  },
  onLoad(options) {
    // #ifdef MP-WEIXIN
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    // 获取胶囊按钮信息
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    // 计算状态栏高度：系统状态栏高度 + 胶囊按钮高度 + 额外间距
    this.statusBarHeight = (systemInfo.statusBarHeight || 0) + (menuButtonInfo.height || 32) + 8
    // #endif
    
    const raw = options?.class_id ?? options?.id;
    let cid = 0;
    if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
      const n = Number(raw);
      cid = Number.isNaN(n) ? 0 : n;
    }
    this.classId = cid;
    // 拉取二级分类标签（pid!=0）
    this.fetchCategoryTags();
    // 拉取列表
    this.fetchGoodsList(true);
  },
  methods: {
    // 返回goods的index页面
    goBack() {
      uni.navigateTo({
        url: '/pages/goods/index'
      });
    },
    
    async fetchCategoryTags() {
      try {
        let res;
        // 使用已导入的 goodsApi
        res = await goodsApi.getGoodsClass();
        
        const list = Array.isArray(res?.data) ? res.data : [];
        const mapped = list.map(item => ({ id: item.id, name: item.name, pid: Number(item.pid) || 0, icon: item.icon }));
        this.categoryTags = mapped.filter(it => it.pid !== 0);
        // 高亮与当前 classId 对应的标签（如存在）
        if (this.classId) {
          const idx = this.categoryTags.findIndex(it => Number(it.id) === Number(this.classId));
          if (idx >= 0) this.selectedCategoryIndex = idx;
        } else {
          this.selectedCategoryIndex = 0;
        }
      } catch (e) {
        console.error('获取分类标签失败:', e);
      }
    },
    async fetchGoodsList(reset = false) {
      if (this.loading) return;
      if (reset) {
        this.page = 1;
        this.hasMore = true;
        this.goodsList = [];
      }
      if (!this.hasMore) return;
      this.loading = true;
      try {
        const class_id = this.getSelectedClassId();
        const type = this.getSelectedType();
        let res;
        // 使用已导入的 goodsApi
        res = await goodsApi.getGoodsList({ class_id, type, kwd: this.kwd, page: this.page, size: this.size });
        const list = Array.isArray(res?.data) ? res.data : [];
        this.goodsList = this.goodsList.concat(list);
        if (!list.length || list.length < this.size) {
          this.hasMore = false;
        } else {
          this.page += 1;
        }
      } catch (err) {
        console.error('获取商品列表失败:', err);
        uni.showToast({ title: err.message || '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    onScrollToLower() {
      this.fetchGoodsList(false);
    },
    getSelectedClassId() {
      // 优先使用从路由传入的后台分类ID
      return this.classId ?? 0;
    },
    getSelectedType() {
      // 优先使用搜索时强制的 type 值
      if (this.forcedType !== undefined) return this.forcedType;
      // 根据二级筛选映射 type；示例：全部-0，自动充值-1，卡密充值-2（如需保持 undefined 为全部，可将 all 映射改回 undefined）
      const map = { all: 0, auto: 1, card: 2 };
      const key = this.subFilters[this.selectedSubFilterIndex]?.id;
      return map[key];
    },
    onSearch() {
      // 点击搜索：按需求 class_id 与 type 默认为 0，关键词为 kwd，分页重置
      this.classId = 0;
      this.forcedType = 0;
      this.fetchGoodsList(true);
    },
    onCategoryTagClick(category, index) {
      this.selectedCategoryIndex = index;
      // 与顶部标签联动：设置后端分类ID并刷新
      const cid = category?.id;
      if (cid !== undefined && cid !== null) {
        this.classId = Number(cid) || 0;
      }
      // 选择分类后自动收起展开效果
      this.isExpanded = false;
      this.fetchGoodsList(true);
    },
    onFilterTabClick(tab, index) {
      this.selectedFilterIndex = index;
      // 如有排序字段，可在这里调整参数后刷新
      this.fetchGoodsList(true);
    },
    onSubFilterClick(filter, index) {
      this.selectedSubFilterIndex = index;
      this.fetchGoodsList(true);
    },
    onGoodsClick(goods) {
      const id = goods?.id || goods?.goods_id;
      if (!id) {
        uni.showToast({ title: '未获取到商品ID', icon: 'none' });
        return;
      }
      // 获取商品类型，如果没有则默认为1（直冲商品）
      const type = goods?.type || 1;
      // 跳转到详情页，传递商品ID和类型
      uni.navigateTo({
        url: `/pages/goods/goodsdetail?type=${encodeURIComponent(type)}&id=${encodeURIComponent(id)}`
      });
    },
    toggleCategoryExpand() {
      this.isExpanded = !this.isExpanded;
    },
    safeImgUrl(url) {
      if (!url) return '';
      return String(url).trim().replace(/`/g, '');
    },
    // 跳转到搜索页面
    goToSearch() {
      uni.navigateTo({
        url: '/pages/index/search'
      });
    }
  }
}
</script>

<style scoped>
/* 状态栏样式 */
.status-bar {
  width: 100%;
  background: linear-gradient(180deg, #FF7B80 0%, rgba(244,234,234,0) 100%);
}

.goods-list-page {
  min-height: 100vh;
  width: 752rpx;
  margin: 0 auto;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 搜索栏样式 */
.search-section {
  background-color: #ffffff;
  padding: 24rpx 24rpx 0;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 2rpx;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.search-input {
  flex: 1;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  gap: 16rpx;
  position: relative;
}

.search-real-input {
  flex: 1;
  height: 100%;
  border: none;
  background: transparent;
  outline: none;
  font-size: 28rpx;
  color: #333333;
  padding-right: 120rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  flex-shrink: 0;
}

.search-placeholder {
  font-size: 28rpx;
  color: #999999;
  flex: 1;
}

.search-btn {
  background-color: #ff4757;
  border-radius: 32rpx;
  width: 100rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 12rpx;
  top: 50%;
  transform: translateY(-50%);
}

.search-btn-text {
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 500;
}

/* 分类标签栏样式 */
.category-tags {
  position: relative;
  background-color: #ffffff;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.category-scroll {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
}

.category-scroll.expanded {
  overflow-x: visible;
  overflow-y: visible;
}

.category-tags-container {
  display: flex;
  gap: 32rpx;
  padding: 28rpx;
  white-space: nowrap;
  flex-wrap: nowrap;
}

.category-tags-container.expanded {
  flex-wrap: wrap;
  min-width: auto;
  width: 100%;
  margin-left: 0;
  padding: 28rpx 24rpx;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 0;
}

.category-tag {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  min-width: 140rpx;
  max-width: 180rpx;
  flex-shrink: 0;
}

.category-tags-container.expanded .category-tag {
  width: 20%;
  margin-bottom: 20rpx;
  min-width: 0;
  max-width: none;
  flex: 0 0 20%;
  box-sizing: border-box;
}

.category-circle {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  background-color: #e8e8e8;
  border: 4rpx solid transparent;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}

.category-circle.active {
  border-color: #ff4757;
}

.category-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.category-text {
  font-size: 22rpx;
  color: #333333;
  text-align: center;
  transition: color 0.2s;
  line-height: 1.3;
  word-break: keep-all;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  min-height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 100%;
}

.category-tags-container.expanded .category-text {
  font-size: 20rpx;
  min-height: 36rpx;
  line-height: 1.2;
}

.category-text.active {
  color: #ffffff;
  font-weight: 500;
  background-color: #ff4757;
  border-radius: 22rpx;
  min-height: 44rpx;
  white-space: nowrap;
}

.category-tags-container.expanded .category-text.active {
  padding: 4rpx 8rpx;
  border-radius: 18rpx;
  min-height: 36rpx;
  font-size: 20rpx;
}

.expand-btn {
  position: absolute;
  top: 36%;
  right: 0rpx;
  transform: translateY(-50%);
  padding: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  z-index: 999;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.expand-text {
  font-size: 24rpx;
  color: #666666;
  writing-mode: vertical-rl;
  text-orientation: upright;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.expand-icon {
  width: 32rpx;
  height: 32rpx;
  transform: rotate(0deg);
  transition: transform 0.3s ease;
}

.expand-icon.rotated {
  transform: rotate(180deg);
}

/* 筛选栏样式 */
.filter-section {
  background-color: #ffffff;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-tabs {
  display: flex;
  gap: 32px;
}

.filter-tab {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 0;
  cursor: pointer;
}

.filter-text {
  font-size: 14px;
  color: #333333;
  transition: color 0.2s;
}

.filter-text.active {
  color: #ff4757;
  font-weight: 500;
}

.sort-icons {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.sort-icon {
  width: 8px;
  height: 6px;
  opacity: 0.5;
  transition: opacity 0.2s;
}

.filter-tab.active .sort-icon {
  opacity: 1;
}

/* 二级筛选标签样式 */
.sub-filter-section {
  background-color: #ffffff;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.sub-filter-scroll {
  width: 100%;
}

.sub-filter-container {
  display: flex;
  gap: 12px;
  padding: 0 16px;
  white-space: nowrap;
}

.sub-filter-tag {
  padding: 0.2rem 0.39rem;
  background-color: #f5f5f5;
  border-radius: 16px;
  transition: all 0.2s;
}

.sub-filter-tag.active {
  background-color: #ff4757;
}

.sub-filter-text {
  font-size: 13px;
  color: #666666;
  transition: color 0.2s;
}

.sub-filter-text.active {
  color: #ffffff;
}

/* 商品列表样式 */
.goods-list {
  flex: 1;
  background-color: #ffffff;
}

.goods-scroll {
  height: 100%;
}

.goods-container {
  padding: 16px;
}

.goods-item {
  display: flex;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 80px;
  height: 80px;
  background-color: #f5f5f5;
  border-radius: 8px;
  position: relative;
  flex-shrink: 0;
  overflow: hidden;
}
.goods-img {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}
.loading-section,
.no-more-section,
.empty-section {
  padding: 12px 0;
  text-align: center;
  color: #999;
  font-size: 12px;
}

.goods-badge {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #333333;
  color: #ffffff;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px 0 4px 0;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.goods-title {
  font-size: 14px;
  color: #333333;
  line-height: 1.4;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-stock {
  font-size: 12px;
  color: #999999;
}

.goods-price-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: auto;
}

.goods-price {
  font-size: 18px;
  color: #ff4757;
  font-weight: 600;
}

.goods-original-price {
  font-size: 12px;
  color: #999999;
  text-decoration: line-through;
  margin-left: -6.2rem;
}

.buy-btn {
  background-color: #ff4757;
  border-radius: 16px;
  padding: 6px 16px;
}

.buy-text {
  color: #ffffff;
  font-size: 12px;
  font-weight: 500;
}

/* 底部指示器 */
.home-indicator {
  height: 34px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.home-indicator::after {
  content: '';
  width: 134px;
  height: 5px;
  background-color: #000000;
  border-radius: 3px;
}
</style>